﻿using GLWrap.MathExt;
using Sharp3D.Math.Core;
using Tao.OpenGl;
using GLWrap.SceneObjects.Line;
using System.Diagnostics;
using ReAnimation.Helpers.Common;

namespace GLWrap.SceneObjects
{
    public class SimpleLine : BaseLine
    {
        private float _length;
        private float _yAngle;
        private float _xAngle;
        private GluQuadricObject _gluQuadricObject;

        public SimpleLine()
        {
            PointA = new Vector3F(0, 0, 0);
            PointB = new Vector3F(1, 1, 1);
        }

        protected override void InternalLineWillBeDrawn(GlSceneManager sceneManager)
        {
            Glu.gluCylinder(_gluQuadricObject.Quadric, Weight, Weight, _length, 10, 10);
        }

        protected override void InternalLineAttachedToScene(GlSceneManager sceneManager)
        {
            _gluQuadricObject = new GluQuadricObject();
        }

        protected override void InternalLineDetachedFromScene(GlSceneManager sceneManager)
        {
            _gluQuadricObject.Dispose();
        }

        protected override void InternalRecalculateLineForSceneManager(GlSceneManager sceneManager)
        {
            MarkAsClean();
            
            Vector3F originalV = new Vector3F(0, 0, 1);
            Vector3F line = PointB - PointA;

            _length = line.GetLength();

            float rotationAngle = MathHelper.GetDegreesBetweenVectors(originalV, line);
            Vector3F axis = Vector3F.CrossProduct(originalV,line);
            axis.Normalize();

            Matrix4F rotMat = Matrix4FExtension.RotationMatrix(rotationAngle, axis);

            if (!MathHelper.GetDegreesBetweenVectors(rotMat.Multiply(originalV),line).EqualWithEpsilan(0,0.1f))
                rotMat = Matrix4FExtension.RotationMatrix(rotationAngle, -axis);

            Matrix4F translateMat = Matrix4FExtension.TranslateMatrix(PointA);

            TransformationMatrix = translateMat * rotMat;
        }
       
    }
}
